package com.togo.algorithm.easy.link;

import com.togo.algorithm.common.ListNode;
import com.togo.algorithm.util.ArrayUtil;
import com.togo.algorithm.util.ListNodeUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author taiyn
 * @Description 输入一个链表的头节点，从尾到头反过来返回每个节点的值（用数组返回）。
 * 示例 1：
 *
 * 输入：head = [1,3,2]
 * 输出：[2,3,1]
 * @Date 10:56 AM 2023/5/23
 **/
public class Offer06 {
    /**
     * 递归实现
     * @param head
     * @return
     */
    public int[] reversePrintByCur(ListNode head) {
        List<Integer> list = new ArrayList<>();
        cur(head, list);

        int[] arr = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            arr[i] = list.get(i);
        }

        return arr;
    }

    private void cur(ListNode node, List<Integer> list) {
        if (node == null) return;
        cur(node.next, list);
        list.add(node.val);
    }

    public int[] reversePrintByStack(ListNode head) {
        LinkedList<Integer> stack = new LinkedList<>();

        ListNode node = head;
        while (node != null) {
            stack.addLast(node.val);
            node = node.next;
        }

        int size = stack.size();
        int[] arr = new int[size];
        for (int i = 0; i < size; i++) {
            arr[i] = stack.removeLast();
        }

        return arr;
    }

    public static void main(String[] args) {
        Offer06 offer06 = new Offer06();
        int[] arr = {1, 3, 2};
        ListNode listNode = ListNodeUtil.buildByArray(arr);
        int[] result = offer06.reversePrintByStack(listNode);

        ArrayUtil.print(result);
    }
}
